package com.yuanli.cosmeticmirror.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.kongzue.dialog.v3.BottomMenu;
import com.rxjava.rxlife.RxLife;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yuanli.cosmeticmirror.R;
import com.yuanli.cosmeticmirror.base.BaseActivity;
import com.yuanli.cosmeticmirror.model.iview.IFeedBackView;
import com.yuanli.cosmeticmirror.persenter.FeedbackPersenter;
import com.yuanli.cosmeticmirror.utils.UriUtils;
import com.yuanli.cosmeticmirror.view.adapter.FeedbackAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;

/**
 * 问题反馈
 */
public class FeedbackActivity extends BaseActivity implements IFeedBackView {
    @BindView(R.id.feedback_back)
    ImageView feedbackBack;
    @BindView(R.id.feedback_enter)
    TextView feedbackEnter;
    @BindView(R.id.feedback_rv)
    RecyclerView feedbackRv;
    @BindView(R.id.feedback_edit)
    EditText feedbackEdit;

    private FeedbackAdapter adapter;
    private static final int REQ_TAKE_PHOTO = 10001;
    private static final int REQ_SELECT_PHOTO = 10002;
    private File imgFile;
    private FeedbackPersenter persenter;

    private long mLastClickTime = 0;
    public final long TIME_INTERVAL = 1000L;

    @Override
    protected int getContentView() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void init(Bundle bundle) {
        persenter = new FeedbackPersenter(this, this);
    }

    @Override
    protected void initView() {
        adapter = new FeedbackAdapter();
        feedbackRv.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (adapter.getData().size() >= 2) {
                    showToast("只能上传一张图片");
                    return;
                }
                showSelectDialog();
            }
        });
    }

    @Override
    protected void initData() {
        adapter.addData("");
    }

    @Override
    protected void destroy() {

    }


    @OnClick({R.id.feedback_back, R.id.feedback_enter})
    public void onViewClicked(View view) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickTime < TIME_INTERVAL) {
            // do something
            return;
        }
        mLastClickTime = nowTime;
        switch (view.getId()) {
            case R.id.feedback_back:
                finish();
                break;
            case R.id.feedback_enter:
                String describe = feedbackEdit.getText().toString();
                if (TextUtils.isEmpty(describe)) {
                    showToast("请填写您想要反馈的问题");
                    return;
                }
                if (describe.length() < 5) {
                    showToast("最少需要填写5字，请尽量描述清楚");
                    return;
                }
                showLoadDialog();
                if (imgFile != null && imgFile.exists()) {
                    persenter.getToken(describe, imgFile.getAbsolutePath());
                    return;
                }
                persenter.upload(describe, "");
                break;
            default:
                break;
        }
    }

    /**
     * 选择照片人脸弹框
     */
    private void showSelectDialog() {
        String[] items = {"拍照", "从相册选择"};
        BottomMenu.show(FeedbackActivity.this, items, (text, index) -> checkAppPermission(index));
    }

    /**
     * 拍照获取
     */
    public void takePhoto() {
        String imgDri = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DCIM" + File.separator;
        String name = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss", Locale.CHINESE).format(new Date()) + ".jpg";
        imgFile = new File(imgDri + name);
        if (!imgFile.getParentFile().exists()) {
            imgFile.getParentFile().mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, UriUtils.file2Uri(getApplicationContext(), imgFile));
        startActivityForResult(intent, REQ_TAKE_PHOTO);
    }

    /**
     * 从图库获取
     */
    public void selectPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQ_SELECT_PHOTO);
    }

    private void checkAppPermission(int index) {
        new RxPermissions(this).request(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribeOn(Schedulers.io())
                .as(RxLife.asOnMain(this))
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        if (index == 0) {
                            takePhoto();
                        } else {
                            selectPhoto();
                        }
                    } else {
                        showToast("请求权限失败");
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQ_TAKE_PHOTO://拍照
                    if (imgFile.exists()) {
                        addImg();
                    }
                    break;
                case REQ_SELECT_PHOTO://图库
                    if (data != null) {
                        Uri sourceUri = data.getData();
                        if (sourceUri != null) {
                            imgFile = UriUtils.uri2File(getApplicationContext(), sourceUri);
                        } else {
                            showToast("选取照片失败");
                            return;
                        }
                        if (imgFile == null) {
                            return;
                        }

                        addImg();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void addImg() {
        adapter.addData(0, imgFile.getAbsolutePath());
        if (adapter.getData().size() == 5) {
            adapter.remove(4);
        }
    }

    @Override
    public void onSucess(int code) {
        dialogDismiss();
        if (code == 1) {
            showToast("问题反馈提交成功");
            finish();
        }

    }

    @Override
    public void onError() {
        dialogDismiss();
        showToast("问题反馈提交失败");
    }

}
